import storage from 'store'
import { login, getInfo, logout } from '@/api/login'
import { welcome } from '@/utils/util'
import { ACCESS_TOKEN, REFRESH_TOKEN } from '@/store/mutation-types'
import qs from 'qs'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    roleid: '',
    info: {},
    userid: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_ROLEID: (state, roleid) => {
      state.roleid = roleid
    },
    SET_USERID: (state, userid) => {
      state.userid = userid
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(qs.stringify(userInfo)).then(response => {
          const result = response
          storage.set(ACCESS_TOKEN, result.token_type + ' ' + result.access_token, 7 * 24 * 60 * 60 * 1000)
          storage.set(REFRESH_TOKEN, result.refresh_token)
          commit('SET_TOKEN', result.access_token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response.data

          if (result.RoleList && result.RoleList.length > 0) {
            commit('SET_ROLES', result.RoleList)
            commit('SET_INFO', result)
            commit('SET_NAME', { name: result.UserName, welcome: welcome() })
            commit('SET_AVATAR', result.UserHeadPhoto)
            commit('SET_USERID', result.UserID)
            resolve(response)
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          storage.remove(ACCESS_TOKEN)
          storage.remove(REFRESH_TOKEN)
          resolve()
        }).catch((err) => {
          console.log('logout fail:', err)
          reject(err)
        })
      })
    }

  }
}

export default user
